<template>
    <div>
        <div class="container">
            <el-main>
                <el-form ref="memberFormRef" :rules="memberFormRules" :model="memberForm" :label-width="formLabelWidth">
                    <el-form-item label="ID" prop="id" v-if="false">
                        <el-input v-model="memberForm.id" c/>
                    </el-form-item>
					<!-- 常规信息 -->
					<el-form-item label="头像" prop="icon">
                        <el-input v-model="memberForm.icon" clearable class="handle-input mr10" v-if="false"/>
                        <el-image v-if="masterImageUrl" :src="masterImageUrl" class="masterImage" fit="cover"/>
                        <VAvatarUpload v-bind:selectValue="VAvatar" @avatar="func_loadVAvatarData" />
                    </el-form-item>
					<el-form-item label="登录账户" prop="username">
                        <el-input v-model="memberForm.username" clearable class="handle-input mr10" maxlength="30" show-word-limit/>
                    </el-form-item>
					<el-form-item label="绑定手机号" prop="phone">
                        <el-input v-model="memberForm.phone" clearable class="handle-input mr10" maxlength="11" show-word-limit/>
                    </el-form-item>
					<el-form-item label="会员名称" prop="nickname">
                        <el-input v-model="memberForm.nickname" clearable class="handle-input mr10" maxlength="20"/>
                    </el-form-item>
					<el-form-item label="职业" prop="job">
                        <el-input v-model="memberForm.job" clearable class="handle-input mr10" maxlength="20" v-if="false"/>
                        <el-select v-model="memberForm.job" class="handle-select mr10" placeholder="请选择">
                            <el-option v-for="item in memberJobOption" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"/>
                        </el-select>
                    </el-form-item>
					<el-form-item label="出生日期" prop="birthday">
                        <el-date-picker type="date" placeholder="选择日期" v-model="memberForm.birthday" class="handle-input mr10" />
                    </el-form-item>
					<el-form-item label="所在城市" prop="city">
                        <el-input v-model="memberForm.city" clearable class="handle-input mr10" v-if="false"/>
                        <el-cascader v-model="provinceOptionVal"
                                @focus="func_loadProvinceOptions" @change="func_setProvince"
                                :options="provinceOptions" :props="provinceOptionProps" placeholder="所在城市" clearable size="medium" style="width:350px" />
                    </el-form-item>
					<el-form-item label="初始积分" prop="integral">
                        <el-input v-model="memberForm.integral" clearable class="handle-input mr10" maxlength="9"/>
                    </el-form-item>
                </el-form>
            </el-main>
			<el-footer>
				<el-button type="primary" @click="func_onSubmit" plain>保存数据</el-button>
				<el-button type="success" @click="func_onReset" plain>重置表单</el-button>
				<el-button @click="func_closeDialog" plain>取 消</el-button>
			</el-footer>
        </div>
    </div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { findMemberList, findMemberInfoById, addMemberInfo, saveMemberInfo} from '../../../../api/hairmanager/member';
import { loadIntegralWayEnum, loadProvTrees, findChildDictionaryListByParentId } from '../../../../api/dict';

import VAvatarUpload from '../../../../components/AvatarUpload.vue';

import { NO_DATA_SELECT_ERROR, SUCCESS_ADDDATA_DIALOG_MESSAGE, SUCCESS_DELDATA_DIALOG_MESSAGE, SUCCESS_EDITDATA_DIALOG_MESSAGE, formLabelWidth, } from "../../../../api/CommonErrorMessage.js";

export default {
    name: "memberIntelInfo",
    components: {VAvatarUpload,},
	props:{
		selectValue: Object
	},
	emits: ["memberData"],
    setup(props, cex){
		onMounted(() => {
		});

        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
        const loadFlg = ref(false);
		/**
         * @name 定义业务表单
         */
        const getInitFormData = () => {
            return {
                birthday: '',
                channel: 0,
                city: '',
                createTime: '',
                educationBackground: '',
                feature: '',
                gender: 0,
                icon: '',
                id: 0,
                integral: 0,
                job: '',
                lastHairTime: '',
                longHair: '',
                managerStatus: 0,
                nextPreHairTime: '',
                nickname: '',
                password: '',
                personalizedSignature: '',
                phone: '',
                sourceType: 0,
                status: 0,
                username: '',
                wechatOpenId: ''
            }
        };
		// const memberIdOpt = ref([]);
		// const memberIntelWayOpt = ref([]);
        const memberJobOption = ref([]);
        /**
         * @name 表单初始化
         */
        const resetMemberForm = () => {
            Object.assign(memberForm, getInitFormData());
        };
		const memberForm = reactive(getInitFormData());
		const memberFormRef = ref(null);
        const memberFormRules = {
            nickname: [
                { required: true, message: "请输入会员名称", trigger: "blur" },
            ],
            username: [
                { required: true, message: "请输入会员登录账户", trigger: "blur" },
            ],
        };
		// =========================================================================================
        const provinceOptionVal = ref('');
		const provinceOptions = ref([]);
        const provinceOptionProps = {
            checkStrictly: true,
        }
		const func_loadProvinceOptions = () => {
			loadProvTrees().then((res) => {
				provinceOptions.value = res.data;
			});
		};
		const func_setProvince = () => {
            memberForm['city'] = provinceOptionVal.value.join(',');
		};
        // =========================================================================================
        const func_loadMemberJobOptions = () => {
            let query = {parentId: 21};
            findChildDictionaryListByParentId(query).then((res) => {
                res.data.list.forEach((item) => {
                    let obj = {};
                    if(item['dicCode'] === memberForm['job']){
                        obj = {value : item['dicCode'], label : item['dicName'], disabled: true}
                    } else {
                        obj = {value : item['dicCode'], label : item['dicName'], disabled: false}
                    }
                    memberJobOption.value.unshift(obj);
                });
            });
        }
		// 主业务处理 ========================================================================================= START
        // 提交
        const func_onSubmit = () => {
            // 表单校验
            memberFormRef.value.validate((valid) => {
                if (valid) {
                    if(loadFlg.value){
                        saveMemberInfo(memberForm).then((res) => {
							if(res.code != 200) {
								ElMessage.error(res.message);
							} else {
								resetMemberForm();
								ElMessage.success(SUCCESS_EDITDATA_DIALOG_MESSAGE);
								cex.emit('memberData', {state: 1, load: false, data: []});
							}
						});
                    } else {
                        addMemberInfo(memberForm).then((res) => {
							if(res.code != 200) {
								ElMessage.error(res.message);
							} else {
								resetMemberForm();
								ElMessage.success(SUCCESS_ADDDATA_DIALOG_MESSAGE);
								cex.emit('memberData', {state: 1, load: false, data: []});
							}
						});
                    }
                } else {
                    return false;
                }
            });
        };
        // 重置
        const func_onReset = () => {
			resetMemberForm();
        };
		const func_closeDialog = () => {
            cex.emit('memberData', {state: 1, data: []});
        };
        // 页面初始化
        const func_onload = (v) => {
			if(loadFlg.value){
				findMemberInfoById(v).then((res) => {
					Object.keys(memberForm).forEach((item) => {
                        memberForm[item] = res.data[item];
                    });
				});
			} else {
				resetMemberForm();
			}
            func_loadMemberJobOptions();
            func_loadProvinceOptions();
        }
		// 主业务处理 ========================================================================================= END
        // 主图上传 ========================================================================================= START
        let masterImageUrl = ref('');
        const VAvatar = reactive({});
        const func_loadVAvatarData = (v) => {
            if(v['state'] === 1) {
                masterImageUrl.vlaue = v['imgUrl'];
                memberForm['urlPic'] = v['imgUrl'];
            }
        };
        // 主图上传 ========================================================================================= END
        // 扩展业务处理 ========================================================================================= START
        // 扩展业务处理 ========================================================================================= END
        watch(() => props.selectValue, (val) => {
            resetMemberForm();
            let id = val['id'];
            loadFlg.value = val['load'];
            func_onload(id);
        }, {deep: true,immediate: true});
        return {
            // 系统变量
			loadFlg, formLabelWidth, memberFormRules, memberFormRef, memberForm, memberJobOption,
            // =========================================================================================
            provinceOptions, provinceOptionProps, provinceOptionVal, func_setProvince, func_loadProvinceOptions, 
            // =========================================================================================
			resetMemberForm, getInitFormData, func_onload, func_onSubmit, func_onReset, func_closeDialog, func_loadMemberJobOptions,
            // =========================================================================================
            // 图片文件处理
            masterImageUrl, VAvatar, func_loadVAvatarData,
            // =========================================================================================
            // 扩展业务处理
            
        };
    },
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 300px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
</style>